package xcmg.device.service.barcode;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import xcmg.device.dao.entity.DataDictionaryDO;
import xcmg.device.dao.entity.ForwardBarcodeTraceInfoDO;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.PubMaterialsDO;
import xcmg.device.dao.entity.barcode.BarcodeManageDO;
import xcmg.device.dao.entity.barcode.BarcodeWxQueryTimesDO;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.entity.company.CompanySupplierDO;
import xcmg.device.dao.entity.delivery.DeliveryNoteDO;
import xcmg.device.dao.entity.delivery.DeliveryReceiptMaterialDO;
import xcmg.device.dao.entity.logistics.SendBillDO;
import xcmg.device.dao.entity.purchase.PurchaseRequestDetailDO;
import xcmg.device.dao.entity.taskRecord.TaskRecordDO;
import xcmg.device.dao.entity.warehouse.AbnormalInDetailDO;
import xcmg.device.dao.entity.warehouse.WarehouseAreaLocationDO;
import xcmg.device.dao.entity.warehouse.WarehouseDeliveryDetailDO;
import xcmg.device.dao.entity.warehouse.WarehouseDeliveryRecordDO;
import xcmg.device.dao.entity.warehouse.WarehouseInboundDO;
import xcmg.device.dao.entity.warehouse.WarehouseInventoryDO;
import xcmg.device.dao.mapper.BarcodeManageMapper;
import xcmg.device.dao.mapper.BarcodeWxQueryTimesMapper;
import xcmg.device.dao.mapper.BoxupDetailMapper;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.CompanySupplierMapper;
import xcmg.device.dao.mapper.DataDictionaryMapper;
import xcmg.device.dao.mapper.FakeCheckHandleMapper;
import xcmg.device.dao.mapper.ForwardBarcodeTraceInfoMapper;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.dao.mapper.PubMaterialsMapper;
import xcmg.device.dao.mapper.PurchaseRequestDetailMapper;
import xcmg.device.dao.mapper.PurchaseRequestMapper;
import xcmg.device.dao.mapper.delivery.DeliveryNoteMapper;
import xcmg.device.dao.mapper.delivery.DeliveryReceiptMaterialMapper;
import xcmg.device.dao.mapper.initialInventory.InitialInventoryDetailMapper;
import xcmg.device.dao.mapper.logistics.SendBillDetailMapper;
import xcmg.device.dao.mapper.logistics.SendBillMapper;
import xcmg.device.dao.mapper.taskRecord.TaskRecordMapper;
import xcmg.device.dao.mapper.warehouse.AbnormalInDetailMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseAreaLocationDOMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDeliveryDetailMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDeliveryRecordMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseInboundDetailMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseInboundMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseInventoryMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.JsonUtil;
import xcmg.device.infra.StringUtil;
import xcmg.device.infra.enums.BarcodeStatus;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.infra.enums.ForwardBarcodeLableEnum;
import xcmg.device.infra.enums.TaskRecordEnum;
import xcmg.device.infra.exception.CommonBusiExceptions;
import xcmg.device.service.GenDocumentService;
import xcmg.device.service.basic.CommonGenService;
import xcmg.device.service.crm.util.ActionResultUtil;
import xcmg.device.service.delivery.DeliveryNoteService;
import xcmg.device.service.logistics.SendBillService;
import xcmg.device.service.vo.barcode.BarCodeCheckOutInfo;
import xcmg.device.service.vo.barcode.BarCodeCheckSupply;
import xcmg.device.service.vo.barcode.BarCodeCheckView;
import xcmg.device.service.vo.barcode.BarcodeManageVO;
import xcmg.device.service.vo.barcode.BatchPrintVO;
import xcmg.device.service.vo.barcode.BindBarCodeVO;
import xcmg.device.service.vo.barcode.SinglePrintDetailVO;
import xcmg.device.service.vo.barcode.SinglePrintVO;
import xcmg.device.service.vo.barcode.SplitNumVO;
import xcmg.device.service.vo.barcode.SplitPrintVO;
import xcmg.device.service.vo.barcode.TjBarcodeManageInfoVO;
import xcmg.device.service.vo.company.CompanyDealerVO;
import xcmg.device.service.vo.delivery.DeliveryNoteVO;
import xcmg.device.service.vo.purchase.PurchaseInboundPrintVO;
import xcmg.device.service.vo.warehouse.SplitDetailVO;
import xcmg.device.service.vo.warehouse.SplitVO;
import xcmg.device.service.vo.warehouse.UpdatePrintNumVO;
import xcmg.device.service.vo.warehouse.WarehouseDeliveryRecordVO;
import xcmg.device.service.warehouse.CommonService;
import xcmg.device.service.warehouse.WarehouseInboundDetailService;
import xcmg.device.service.warehouse.WarehouseInventorySplitService;
import xcmg.device.util.CompanyUtil;
import yb.ecp.fast.dto.UserCacheDTO;
import yb.ecp.fast.feign.AuthClient;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.PageHelperPlus;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by sqq on 2018/1/24.
 */
@Slf4j
@Service
public class BarcodeService {

    @Autowired
    private BarcodeManageMapper barcodeManageMapper;

    @Autowired
    private BarcodeWxQueryTimesMapper barcodeWxQueryTimesMapper;

    @Autowired
    private ForwardBarcodeTraceInfoMapper forwardBarcodeTraceInfoMapper;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private CommonGenService commonGenService;

    @Autowired
    private DataDictionaryMapper dataDictionaryMapper;

    @Autowired
    private WarehouseInboundDetailService warehouseInboundDetailService;

    @Autowired
    private WarehouseInboundDetailMapper warehouseInboundDetailMapper;

    @Autowired
    private WarehouseInventorySplitService warehouseInventorySplitService;

    @Autowired
    private AuthClient authClient;

    @Autowired
    private WarehouseInboundMapper warehouseInboundMapper;

    @Autowired
    private InitialInventoryDetailMapper initialInventoryDetailMapper;

    @Autowired
    private WarehouseInventoryMapper warehouseInventoryMapper;

    @Autowired
    private PurchaseRequestDetailMapper purchaseRequestDetailMapper;

    @Autowired
    private PurchaseRequestMapper purchaseRequestMapper;

    @Autowired
    private PriMaterialsMapper priMaterialsMapper;

    @Autowired
    private GenDocumentService genDocumentService;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private WarehouseDeliveryDetailMapper warehouseDeliveryDetailMapper;

    @Autowired
    private FakeCheckHandleMapper fakeCheckHandleMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private BarcodeBatchPrintService barcodeBatchPrintService;

    @Autowired
    private WarehouseDeliveryRecordMapper warehouseDeliveryRecordMapper;

    @Autowired
    private TaskRecordMapper taskRecordMapper;

    @Autowired
    private SendBillDetailMapper sendBillDetailMapper;
//
//    @Value("${barcode.prefix.url}")
//    private String barcodePrefixUrl;
//    @Value("${xgwj.fakecheck.handle.url}")
//    private String handleUrl;

    @Autowired
    private DeliveryNoteService deliveryNoteService;
    @Autowired
    private DeliveryNoteMapper deliveryNoteMapper;

    @Autowired
    private PubMaterialsMapper pubMaterialsMapper;

    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    private AbnormalInDetailMapper abnormalInDetailMapper;

    @Autowired
    private DeliveryReceiptMaterialMapper deliveryReceiptMaterialMapper;

    @Autowired
    private BoxupDetailMapper boxupDetailMapper;
    @Autowired
    private WarehouseAreaLocationDOMapper warehouseAreaLocationDOMapper;
    
    @Autowired
    private SendBillMapper sendBillMapper;
    
    @Autowired
    private SendBillService sendBillService;
    
    @Autowired
    private CompanySupplierMapper companySupplierMapper;
    
    @Autowired
    private CompanyUtil companyUtil;

    @Transactional
    public List<BarcodeManageVO>  singlePrint(SinglePrintVO singlePrintVO, String userId, String orgId) throws Exception{

        ActionResult<String> textResult=fastGenClient.textGuid();
        if(textResult.getCode()!=ErrorCode.Success.getCode()){
            singlePrintVO.setErrorCode(ErrorCode.IllegalArument);
            return new ArrayList<>();
        }
        String totalBarcode=textResult.getValue();
        ActionResult userAuth =  authClient.getUserDetail(userId);
        UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
        String userName="";
        if(userInfo!=null){
            userName=userInfo.getName();
        }
        if(StringUtil.isEmpty(singlePrintVO.getBillNo())){
            singlePrintVO.setErrorCode(ErrorCode.AbnormalInNotFound);
            return new ArrayList<>();
        }
        BigDecimal leftNum;
        if(singlePrintVO.getRowNo() != null){
            //配送指令入库单按照行号查
            leftNum= warehouseInboundDetailMapper.leftPrintNumRowNo(singlePrintVO.getBillNo(),singlePrintVO.getRowNo(), orgId,singlePrintVO.getMaterialsNo());
        }else{
            leftNum= warehouseInboundDetailMapper.leftPrintNum(singlePrintVO.getBillNo(),singlePrintVO.getMaterialsNo(), orgId);
        }
        if(singlePrintVO.getTotalQty()==null){
            singlePrintVO.setErrorCode(ErrorCode.BarcodeTotalQtyNull);
            return new ArrayList<>();
        }
        if(singlePrintVO.getTotalQty().equals(BigDecimal.ZERO)){
            singlePrintVO.setErrorCode(ErrorCode.BarcodeTotalQtyError);
            return new ArrayList<>();
        }
        if(singlePrintVO.getTotalQty().compareTo(leftNum)>0){
            singlePrintVO.setErrorCode(ErrorCode.BarcodeLeftNotError);
            return new ArrayList<>();
        }
        
        String billNo = singlePrintVO.getBillNo();
        if(StringUtils.isNotEmpty(billNo)) {
            WarehouseInboundDO warehouseInboundDO = warehouseInboundMapper.selectByOrder(billNo, orgId);
            orgId = warehouseInboundDO.getOrgId();
        }
        
        List<BarcodeManageVO> results=new ArrayList<>();
        BarcodeManageVO barcodeManageVO=new BarcodeManageVO();
        BarcodeManageDO barcodeManageDO=makeTotalSingleBarcode(singlePrintVO,totalBarcode,orgId,userId,userName);
        WarehouseInboundDO inboundDO = warehouseInboundMapper.selectByOrder(barcodeManageDO.getBillNo(), orgId);
        String locationDesc="";
        if(inboundDO!=null){
            locationDesc=barcodeManageMapper.locationDesc(singlePrintVO.getMaterialsNo(),orgId,inboundDO.getWarehouseCode());
        }
        barcodeManageMapper.insert(barcodeManageDO);
        BeanUtils.copyProperties(barcodeManageDO,barcodeManageVO);
        barcodeManageVO.setLocationDesc(locationDesc);
        barcodeManageVO.setBatchNo(barcodeManageDO.getPurchaseContractNo());
        barcodeManageVO.setDestinnation(barcodeManageDO.getCountry());
        convertSupplierCode(barcodeManageVO);
        results.add(barcodeManageVO);
        Integer i=0;
        for (SinglePrintDetailVO detailVO:singlePrintVO.getDetailList()
             ) {
            if(detailVO.getCurrentQty().equals(0)){
                continue;
            }
            i++;
            ActionResult<String> bartextResult=fastGenClient.textGuid();
            if(bartextResult.getCode()!=ErrorCode.Success.getCode()){
                throw  new Exception("异常");
            }
            String barcode=bartextResult.getValue();
            BarcodeManageVO subBarcodeManageVO=new BarcodeManageVO();
            BarcodeManageDO subBarcodeManageDO=makeSubSingleBarcode(singlePrintVO,detailVO,barcode,totalBarcode,orgId,userId,userName,i,0);
            barcodeManageMapper.insert(subBarcodeManageDO);
            BeanUtils.copyProperties(subBarcodeManageDO,subBarcodeManageVO);
            subBarcodeManageVO.setLocationDesc(locationDesc);
            subBarcodeManageVO.setBatchNo(barcodeManageDO.getPurchaseContractNo());
            subBarcodeManageVO.setDestinnation(barcodeManageDO.getCountry());
            convertSupplierCode(subBarcodeManageVO);
            results.add(subBarcodeManageVO);
        }
        UpdatePrintNumVO updatePrintNumVO=new UpdatePrintNumVO();
        updatePrintNumVO.setBusinessOrder(barcodeManageDO.getBillNo());
        updatePrintNumVO.setMaterialsNo(barcodeManageDO.getMaterialsNo());
        updatePrintNumVO.setPrintNum(barcodeManageDO.getTotalQty());
        updatePrintNumVO.setRowNo(barcodeManageDO.getRowNo());
        List<UpdatePrintNumVO> updatePrintNumVOList=new ArrayList<>();
        updatePrintNumVOList.add(updatePrintNumVO);
        warehouseInboundDetailService.updatePrintNum(updatePrintNumVOList, orgId);
        singlePrintVO.setErrorCode(ErrorCode.Success);
        for (BarcodeManageVO result:results
             ) {
            result.setChildCount(i);
        }
        return results;
    }

    public List<BarcodeManageVO> batchPrintForSelect(List<BatchPrintVO> list, String userId, String orgId) throws Exception {
        if (ListUtil.isNullOrEmpty(list)) {
            return new ArrayList<>();
        }
        SinglePrintVO singlePrintVO = new SinglePrintVO();
        SinglePrintDetailVO singlePrintDetailVO = new SinglePrintDetailVO();
        List<SinglePrintDetailVO> detailList = new ArrayList<>();
        List<BarcodeManageVO> results = new ArrayList<>();
        for (BatchPrintVO batchPrintVO : list) {
            detailList.clear();
            singlePrintVO.setMaterialsNo(batchPrintVO.getMaterialsNo());
            singlePrintVO.setMaterialsDes(batchPrintVO.getMaterialsDes());
            singlePrintVO.setTotalQty(batchPrintVO.getTotalQty());
            singlePrintVO.setBillNo(batchPrintVO.getBillNo());
            singlePrintVO.setRowNo(batchPrintVO.getRowNo());
            singlePrintDetailVO.setCurrentQty(batchPrintVO.getTotalQty());
            detailList.add(singlePrintDetailVO);
            singlePrintVO.setDetailList(detailList);

            results.addAll(this.singlePrint(singlePrintVO, userId, orgId));
        }
        return results;
    }

    private BarcodeManageDO makeTotalSingleBarcode(SinglePrintVO singlePrintVO,String totalBarcode,String orgId,String userId,String userName){
        BarcodeManageDO barcodeManageDO=new BarcodeManageDO();
        barcodeManageDO.setBarcode(totalBarcode);
        barcodeManageDO.setTotalBarcode(totalBarcode);
        barcodeManageDO.setOrgId(orgId);
        barcodeManageDO.setBillType(singlePrintVO.getBillType());
        barcodeManageDO.setBillId(singlePrintVO.getBillId());
        barcodeManageDO.setBillNo(singlePrintVO.getBillNo());
        barcodeManageDO.setBarcodeFlag(0);
        barcodeManageDO.setMaterialsNo(singlePrintVO.getMaterialsNo());
        barcodeManageDO.setMaterialsDes(singlePrintVO.getMaterialsDes());
        barcodeManageDO.setTotalQty(singlePrintVO.getTotalQty());
        barcodeManageDO.setCurrentQty(singlePrintVO.getTotalQty());
        barcodeManageDO.setLeftQty(singlePrintVO.getLeftQty());
        barcodeManageDO.setWarehouseCode(singlePrintVO.getWarehouseCode());
        barcodeManageDO.setPrintId(userId);
        barcodeManageDO.setPrintName(userName);
        barcodeManageDO.setPrintTime(new Date());
        barcodeManageDO.setReprintCount(0);
        barcodeManageDO.setBarcodeStatus(BarcodeStatus.Status.Printed.toString());
        barcodeManageDO.setRowNo(singlePrintVO.getRowNo());
        DataDictionaryDO dataDictionaryDO=dataDictionaryMapper.itemByCode(BarcodeStatus.Status.Name.toString(),barcodeManageDO.getBarcodeStatus());
        if(dataDictionaryDO!=null){
            barcodeManageDO.setStatusDesc(dataDictionaryDO.getName());
        }
        barcodeManageDO.setCreateId(userId);
        barcodeManageDO.setCreateName(userName);
        barcodeManageDO.setCreateTime(new Date());
        barcodeManageDO.setIsDel(false);
        barcodeManageDO.setIsSeparate(false);
        barcodeManageDO.setSeq(0);
        //处理进出条码信息
        preJckInfo(barcodeManageDO);
        return barcodeManageDO;
    }

    private BarcodeManageDO makeSubSingleBarcode(SinglePrintVO singlePrintVO,SinglePrintDetailVO detailVO,String barcode,String totalBarcode,String orgId,String userId,String userName,Integer seq, int type){
        BarcodeManageDO subBarcodeManageDO=new BarcodeManageDO();
        subBarcodeManageDO.setBarcode(barcode);
        subBarcodeManageDO.setTotalBarcode(totalBarcode);
        subBarcodeManageDO.setOrgId(orgId);
        subBarcodeManageDO.setBillType(singlePrintVO.getBillType());
        subBarcodeManageDO.setBillNo(singlePrintVO.getBillNo());
        subBarcodeManageDO.setBillId(singlePrintVO.getBillId());
        subBarcodeManageDO.setBarcodeFlag(1);
        subBarcodeManageDO.setBarcodeDesc(detailVO.getBarcodeDesc());
        subBarcodeManageDO.setVinid(detailVO.getVinid());
        subBarcodeManageDO.setOrawyd(detailVO.getOrawyd());
        subBarcodeManageDO.setMaterialsNo(singlePrintVO.getMaterialsNo());
        subBarcodeManageDO.setMaterialsDes(singlePrintVO.getMaterialsDes());
        subBarcodeManageDO.setTotalQty(singlePrintVO.getTotalQty());
        subBarcodeManageDO.setCurrentQty(detailVO.getCurrentQty());
        subBarcodeManageDO.setLeftQty(singlePrintVO.getLeftQty());
        subBarcodeManageDO.setWarehouseCode(singlePrintVO.getWarehouseCode());
        subBarcodeManageDO.setPrintId(userId);
        subBarcodeManageDO.setPrintName(userName);
        subBarcodeManageDO.setPrintTime(new Date());
        subBarcodeManageDO.setReprintCount(0);
        subBarcodeManageDO.setModel(detailVO.getModel());
        subBarcodeManageDO.setRowNo(singlePrintVO.getRowNo());
        if(type == 1){
            subBarcodeManageDO.setBarcodeStatus(BarcodeStatus.Status.OutStorage.toString());
        }else{
            subBarcodeManageDO.setBarcodeStatus(BarcodeStatus.Status.Printed.toString());
        }
        DataDictionaryDO detaildataDictionaryDO=dataDictionaryMapper.itemByCode( BarcodeStatus.Status.Name.toString(),subBarcodeManageDO.getBarcodeStatus());
        if(detaildataDictionaryDO!=null){
            subBarcodeManageDO.setStatusDesc(detaildataDictionaryDO.getName());
        }
        subBarcodeManageDO.setCreateId(userId);
        subBarcodeManageDO.setCreateName(userName);
        subBarcodeManageDO.setCreateTime(new Date());
        subBarcodeManageDO.setRemark(detailVO.getRemark());
        subBarcodeManageDO.setIsDel(false);
        subBarcodeManageDO.setIsSeparate(false);
        subBarcodeManageDO.setSeq(seq);
        preJckInfo(subBarcodeManageDO);
        return subBarcodeManageDO;
    }

    @Transactional(rollbackFor = Exception.class)
    public List<BarcodeManageVO> batchPrint(List<BatchPrintVO> batchPrintVOList,String userId,String orgId) throws Exception{
        List<BarcodeManageVO> barcodeManageVOList=new ArrayList<>();
        List<UpdatePrintNumVO> updatePrintNumVOList=new ArrayList<>();
        ActionResult userAuth =  authClient.getUserDetail(userId);
        UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
        String userName="";
        if(userInfo!=null){
            userName=userInfo.getName();
        }
        for (BatchPrintVO batchPrintVO:batchPrintVOList
             ) {
            if(batchPrintVO.getTotalQty().equals(0)){
                continue;
            }
            ActionResult<String> textResult=fastGenClient.textGuid();
            if(textResult.getCode()!=ErrorCode.Success.getCode()){
                return null;
            }
            String totalBarcode=textResult.getValue();
            BarcodeManageDO barcodeManageDO=makeTotalBatchBarcode(batchPrintVO,totalBarcode,orgId,userId,userName);

            barcodeManageMapper.insert(barcodeManageDO);
            String locationDesc="";
            WarehouseInboundDO inboundDO = warehouseInboundMapper.selectByOrder(barcodeManageDO.getBillNo(), orgId);
            if(inboundDO!=null){
                locationDesc=barcodeManageMapper.locationDesc(batchPrintVO.getMaterialsNo(),orgId,inboundDO.getWarehouseCode());
            }
            BarcodeManageVO barcodeManageVO=new BarcodeManageVO();
            BeanUtils.copyProperties(barcodeManageDO,barcodeManageVO);
            barcodeManageVO.setLocationDesc(locationDesc);
            barcodeManageVOList.add(barcodeManageVO);
            ActionResult<String> subTextResult=fastGenClient.textGuid();
            if(subTextResult.getCode()!=ErrorCode.Success.getCode()){
                return null;
            }
            String subBarcode=subTextResult.getValue();
            BarcodeManageDO subBarcodeManageDO=makeSubBatchBarcode(batchPrintVO,subBarcode,totalBarcode,orgId,userId,userName);

            barcodeManageMapper.insert(subBarcodeManageDO);

            BarcodeManageVO subBarcodeManageVO=new BarcodeManageVO();
            BeanUtils.copyProperties(subBarcodeManageDO,subBarcodeManageVO);
            subBarcodeManageVO.setLocationDesc(locationDesc);
            barcodeManageVOList.add(subBarcodeManageVO);
            UpdatePrintNumVO updatePrintNumVO=new UpdatePrintNumVO();
            updatePrintNumVO.setBusinessOrder(barcodeManageDO.getBillNo());
            updatePrintNumVO.setMaterialsNo(barcodeManageDO.getMaterialsNo());
            updatePrintNumVO.setPrintNum(barcodeManageDO.getTotalQty());
            updatePrintNumVOList.add(updatePrintNumVO);
        }
        warehouseInboundDetailService.updatePrintNum(updatePrintNumVOList, orgId);
        for (BarcodeManageVO result:barcodeManageVOList
                ) {
            result.setChildCount(1);
        }
        return barcodeManageVOList;
    }

    private BarcodeManageDO makeTotalBatchBarcode(BatchPrintVO batchPrintVO,String totalBarcode,String orgId,String userId,String userName){
        BarcodeManageDO barcodeManageDO=new BarcodeManageDO();
        barcodeManageDO.setBarcode(totalBarcode);
        barcodeManageDO.setTotalBarcode(totalBarcode);
        barcodeManageDO.setOrgId(orgId);
        barcodeManageDO.setBillType(batchPrintVO.getBillType());
        barcodeManageDO.setBillId(batchPrintVO.getBillId());
        barcodeManageDO.setBillNo(batchPrintVO.getBillNo());
        barcodeManageDO.setBarcodeFlag(0);
        barcodeManageDO.setMaterialsNo(batchPrintVO.getMaterialsNo());
        barcodeManageDO.setMaterialsDes(batchPrintVO.getMaterialsDes());
        barcodeManageDO.setTotalQty(batchPrintVO.getTotalQty());
        barcodeManageDO.setCurrentQty(batchPrintVO.getTotalQty());
        barcodeManageDO.setLeftQty(new BigDecimal(0));
        barcodeManageDO.setWarehouseCode(batchPrintVO.getWarehouseCode());
        barcodeManageDO.setPrintId(userId);
        barcodeManageDO.setPrintName(userName);
        barcodeManageDO.setPrintTime(new Date());
        barcodeManageDO.setReprintCount(0);
        barcodeManageDO.setBarcodeStatus(BarcodeStatus.Status.Printed.toString());
        DataDictionaryDO dataDictionaryDO=dataDictionaryMapper.itemByCode(BarcodeStatus.Status.Name.toString(),barcodeManageDO.getBarcodeStatus());
        if(dataDictionaryDO!=null){
            barcodeManageDO.setStatusDesc(dataDictionaryDO.getName());
        }
        barcodeManageDO.setCreateId(userId);
        barcodeManageDO.setCreateName(userName);
        barcodeManageDO.setCreateTime(new Date());
        barcodeManageDO.setIsDel(false);
        barcodeManageDO.setIsSeparate(false);
        barcodeManageDO.setSeq(0);
        return barcodeManageDO;
    }

    private BarcodeManageDO makeSubBatchBarcode(BatchPrintVO batchPrintVO,String subBarcode,String totalBarcode,String orgId,String userId,String userName){
        BarcodeManageDO subBarcodeManageDO=new BarcodeManageDO();
        subBarcodeManageDO.setBarcode(subBarcode);
        subBarcodeManageDO.setTotalBarcode(totalBarcode);
        subBarcodeManageDO.setOrgId(orgId);
        subBarcodeManageDO.setBillType(batchPrintVO.getBillType());
        subBarcodeManageDO.setBillId(batchPrintVO.getBillId());
        subBarcodeManageDO.setBillNo(batchPrintVO.getBillNo());
        subBarcodeManageDO.setBarcodeFlag(1);
        subBarcodeManageDO.setMaterialsNo(batchPrintVO.getMaterialsNo());
        subBarcodeManageDO.setMaterialsDes(batchPrintVO.getMaterialsDes());
        subBarcodeManageDO.setTotalQty(batchPrintVO.getTotalQty());
        subBarcodeManageDO.setCurrentQty(batchPrintVO.getTotalQty());
        subBarcodeManageDO.setLeftQty(new BigDecimal(0));
        subBarcodeManageDO.setWarehouseCode(batchPrintVO.getWarehouseCode());
        subBarcodeManageDO.setPrintId(userId);
        subBarcodeManageDO.setPrintName(userName);
        subBarcodeManageDO.setPrintTime(new Date());
        subBarcodeManageDO.setReprintCount(0);
        subBarcodeManageDO.setBarcodeStatus(BarcodeStatus.Status.Printed.toString());
        DataDictionaryDO subDataDictionaryDO=dataDictionaryMapper.itemByCode( BarcodeStatus.Status.Name.toString(),subBarcodeManageDO.getBarcodeStatus());
        if(subDataDictionaryDO!=null){
            subBarcodeManageDO.setStatusDesc(subDataDictionaryDO.getName());
        }
        subBarcodeManageDO.setCreateId(userId);
        subBarcodeManageDO.setCreateName(userName);
        subBarcodeManageDO.setCreateTime(new Date());
        subBarcodeManageDO.setIsDel(false);
        subBarcodeManageDO.setIsSeparate(false);
        subBarcodeManageDO.setSeq(1);
        return subBarcodeManageDO;
    }

    public PageCommonVO list(SearchCommonVO<BarcodeManageVO> condition) {
        if (StringUtils.isNotBlank(condition.getFilters().getDeliveryReceiptNo())) {
            getByReceipt(condition.getFilters());
        }
        if (!ObjectUtils.isEmpty(condition.getFilters().getMaterialNos())) {
            List<String> materialNoList = Arrays.asList(condition.getFilters().getMaterialNos().split(","));
            condition.getFilters().setMaterialNoList(materialNoList);
        }

        WarehouseInboundDO warehouseInboundDO = warehouseInboundMapper.
                selectByOrder(condition.getFilters().getBillNo(), condition.getFilters().getOrgId());
        if (warehouseInboundDO != null) {
            condition.getFilters().setOrgId(warehouseInboundDO.getOrgId());
        }
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(condition.getFilters().getOrgId());
        String sapCode = companyInfoDO.getSapCode();
        PageCommonVO pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_time desc,barcode");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<BarcodeManageDO> barcodeManageDOList = barcodeManageMapper.list(condition.getFilters());
        List<BarcodeManageVO> barcodeManageVOList = new ArrayList<>();
        Set<String> materialsNoList = new HashSet<>();
        for (BarcodeManageDO barcodeManageDO : barcodeManageDOList) {
            BarcodeManageVO barcodeManageVO = new BarcodeManageVO();
            BeanUtils.copyProperties(barcodeManageDO, barcodeManageVO);
            String locationDesc = "";
            //矿机的单处理http://10.90.1.198/zentao/story-view-3024.html 如果条码第一次被打印后，后面经过了移库等操作，这个条码不在此储位上了，换储位了，但是补打的时候扔记录初始储位，没有根据实际库存所在的储位显示。
            if (sapCode != null && CompanyUtil.KJ_SAP_CODE.equals(sapCode)) {
                WarehouseInventoryDO inventoryDO = warehouseInventoryMapper.selectByBarCode(barcodeManageDO.getBarcode(), barcodeManageDO.getOrgId());
                if(inventoryDO!=null&&inventoryDO.getLocationCode()!=null){
                    WarehouseAreaLocationDO location = warehouseAreaLocationDOMapper.item(inventoryDO.getLocationCode(), barcodeManageDO.getOrgId());
                    locationDesc=location == null ? null : location.getLocationDesc();
                }
            }else{
                WarehouseInboundDO inboundDO = warehouseInboundMapper.selectByOrder(barcodeManageDO.getBillNo(), barcodeManageDO.getOrgId());
                if(inboundDO!=null&&inboundDO.getWarehouseCode()!=null){
                    locationDesc=barcodeManageMapper.locationDesc(barcodeManageDO.getMaterialsNo(),barcodeManageDO.getOrgId(),inboundDO.getWarehouseCode());
                }
            }
            barcodeManageVO.setLocationDesc(locationDesc);
            barcodeManageVO.setChildCount(barcodeManageMapper.findChildCount(barcodeManageVO.getTotalBarcode()));
            if (barcodeManageVO.getBusinessOrder() != null && barcodeManageVO.getBusinessOrder().startsWith("XGFT")){
                //发运交接单
                DeliveryNoteVO deliveryNoteVO = deliveryNoteService.itemDetail(barcodeManageVO.getBusinessOrder(), barcodeManageVO.getOrgId(), barcodeManageVO.getMaterialsNo());
                barcodeManageVO.setDestinnation(deliveryNoteVO.getCountry());
                barcodeManageVO.setOriginalMaterialsNo(deliveryNoteVO.getOriginalMaterialsNo());
                if (CompanyUtil.JCK_SAP_CODE.equals(sapCode)){//进出口
                    barcodeManageVO.setBatchNo(barcodeManageDO.getPurchaseContractNo());
                    barcodeManageVO.setMachineModel(barcodeManageDO.getMachineModel());
                }else{
                    barcodeManageVO.setBatchNo(deliveryNoteVO.getPurchaseContractNo());
                    barcodeManageVO.setMachineModel(deliveryNoteVO.getMachineModel());
                }
            }else{
                //发运交接单
                if (barcodeManageVO.getDeliveryReceiptNo() != null && barcodeManageVO.getDeliveryReceiptNo().startsWith("XGFJ")) {
                    DeliveryReceiptMaterialDO materialDO = deliveryReceiptMaterialMapper.findByMaterialNo(barcodeManageVO.getDeliveryReceiptNo(), barcodeManageDO.getMaterialsNo());
                    if (materialDO != null) {
                        barcodeManageVO.setOriginalMaterialsNo(materialDO.getOriginalMaterialsNo());
                    }
                }
                //查询发运交接单
                if (StringUtils.isNotEmpty(sapCode)){
                    if (CompanyUtil.JCK_SAP_CODE.equals(sapCode)){//进出口
                        barcodeManageVO.setBatchNo(barcodeManageDO.getPurchaseContractNo());
                        barcodeManageVO.setMachineModel(barcodeManageDO.getMachineModel());
                        barcodeManageVO.setDestinnation(barcodeManageDO.getCountry());
                    }
                }else{
                    CompanyDealerVO companyDealerVO = new CompanyDealerVO();
                    companyDealerVO.setPlatOrgId(barcodeManageVO.getOrgId());
                    List<CompanyDealerDO> dealerDOList = companyDealerMapper.list(companyDealerVO);
                    convertSupplierCode(barcodeManageVO);
                    if (!CollectionUtils.isEmpty(dealerDOList)){
                        List<String> orgIds = dealerDOList.stream().map(CompanyDealerDO::getOrgId).collect(Collectors.toList());
                        List<CompanyInfoDO> companyInfoDOList = companyInfoMapper.selectBatchByOrgIds(orgIds);
                        //二级代理商出现null
                        boolean flag = companyInfoDOList.stream()
                                .anyMatch(info->info.getSapCode() != null && info.getSapCode().equals(CompanyUtil.JCK_SAP_CODE));
                        if (flag){
                            barcodeManageVO.setBatchNo(barcodeManageDO.getPurchaseContractNo());
                            barcodeManageVO.setMachineModel(barcodeManageDO.getMachineModel());
                            barcodeManageVO.setDestinnation(barcodeManageDO.getCountry());
                        }
                    }
                }

            }
            materialsNoList.add(barcodeManageVO.getMaterialsNo());
            barcodeManageVOList.add(barcodeManageVO);
        }

        //零件英文描述
        if (materialsNoList.size() > 0) {
            Map<String, PubMaterialsDO> pubMaterialsDOMap = pubMaterialsMapper.selectByMaterialsNos(new ArrayList<>(materialsNoList))
                    .stream().collect(Collectors.toMap(PubMaterialsDO::getMaterialsNo, a -> a, (k1, k2) -> k1));
            for (BarcodeManageVO barcodeManageVO : barcodeManageVOList) {
                if (pubMaterialsDOMap.containsKey(barcodeManageVO.getMaterialsNo()) && pubMaterialsDOMap.get(barcodeManageVO.getMaterialsNo()) != null) {
                    PubMaterialsDO pubMaterialsDO = pubMaterialsDOMap.get(barcodeManageVO.getMaterialsNo());
                    barcodeManageVO.setMaterialsDesEn(pubMaterialsDO.getMaterialsDesEn());
                }
            }
        }

        pageCommonVO.setPageInfo(new PageInfo(barcodeManageDOList));
        pageCommonVO.setPageInfoList(barcodeManageVOList);
        return pageCommonVO;
    }

    private void convertSupplierCode(BarcodeManageVO barcodeManageVO) {
        SendBillDO sendBillDO = sendBillMapper.itemByBillNo(barcodeManageVO.getBillNo());
        if (sendBillDO != null) {
            CompanySupplierDO companySupplierDO = companySupplierMapper.itemBySupplierOrgId(companyUtil.ynOrgId(), sendBillDO.getSoldOrgId());
            if (companySupplierDO != null) {
                barcodeManageVO.setSupplierCode(companySupplierDO.getSupplierCode());
            }
        }
    }

    private void getByReceipt(BarcodeManageVO barcodeManageVO) {
        //根据发运交接单查询关联的出库业务单据的出库条码信息
        List<String> barCodes = warehouseDeliveryRecordMapper.selectBarcodeByReceiptNo(barcodeManageVO.getDeliveryReceiptNo());
        if (CollectionUtils.isEmpty(barCodes)) {
            return;
        }
        barcodeManageVO.setBarcodeList(barCodes);
    }

    public ErrorCode updatePrintCount(List<String> barcodes,String userId, String orgId) throws Exception{
        for (String barcode:barcodes
             ) {
            BarcodeManageDO barcodeManageDO=barcodeManageMapper.item(barcode, orgId);
            if(barcodeManageDO==null){
                //查不到不修改次数
                return ErrorCode.Success;
            }
            ActionResult userAuth =  authClient.getUserDetail(userId);
            UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
            String userName="";
            if(userInfo!=null){
                userName=userInfo.getName();
            }
            barcodeManageDO.setPrintTime(new Date());
            barcodeManageDO.setPrintId(userId);
            barcodeManageDO.setPrintName(userName);
            barcodeManageDO.setReprintCount(barcodeManageDO.getReprintCount()+1);
            barcodeManageDO.setOrgId(orgId);
            barcodeManageMapper.update(barcodeManageDO);
        }
        return ErrorCode.Success;
    }

    /**
     * 更新条码管理中的批次号和供应商编码
     * @param barcodeManageVO 待更新数据
     * @param userId 用户ID
     * @param orgId 机构ID
     * @return 更新结果
     */
    public ErrorCode updateBatchId(BarcodeManageVO barcodeManageVO, String userId, String orgId) {
        if (StringUtils.isBlank(barcodeManageVO.getBarcode())) {
            return ErrorCode.BarcodeNotFound;
        }
        BarcodeManageDO barcodeManageDO = barcodeManageMapper.item(barcodeManageVO.getBarcode(), orgId);
        if (barcodeManageDO == null) {
            return ErrorCode.BarcodeNotFound;
        }
        barcodeManageDO.setSplirid(barcodeManageVO.getSplirid());
        barcodeManageDO.setBatchId(barcodeManageVO.getBatchId());
        barcodeManageMapper.update(barcodeManageDO);
        return ErrorCode.Success;
    }

    public BarcodeManageVO splitNum(SplitNumVO splitNumVO,String userId,String orgId)throws Exception{
        if(splitNumVO.getNum() == null || splitNumVO.getNum().compareTo(BigDecimal.ZERO) == 0){
            throw new Exception("数量不能为0");
        }
        List<WarehouseDeliveryDetailDO> deliveryDetailDOList = warehouseDeliveryDetailMapper.findByBusinessOrder(splitNumVO.getBusinessOrder(), orgId);
        if(ListUtil.isNullOrEmpty(deliveryDetailDOList)){
            throw new Exception("出库单号不正确");
        }
        BarcodeManageDO barcodeManageDO=barcodeManageMapper.item(splitNumVO.getBarcode(), orgId);
        if(barcodeManageDO==null || barcodeManageDO.getIsDel()){
            splitNumVO.setCode(ErrorCode.BarcodeNotFound);
            return null;
        }
        if(!barcodeManageDO.getBarcodeStatus().equals(BarcodeStatus.Status.Printed.toString())&& !barcodeManageDO.getBarcodeStatus().equals(BarcodeStatus.Status.InStorage.toString())){
            splitNumVO.setCode(ErrorCode.BarcodeNotSplit);
            return null;
        }
        if(barcodeManageDO.getCurrentQty().compareTo(splitNumVO.getNum()) <= 0){
            splitNumVO.setCode(ErrorCode.BarcodeNotSplit);
            return null;
        }
        WarehouseDeliveryDetailDO deliveryDetailDO = warehouseDeliveryDetailMapper.itemByMaterialsNo(orgId,splitNumVO.getBusinessOrder(),barcodeManageDO.getMaterialsNo());
        if(deliveryDetailDO == null){
            throw new Exception("此零件不属于此出库单");
        }
        ActionResult userAuth =  authClient.getUserDetail(userId);
        UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
        String userName="";
        if(userInfo!=null){
            userName=userInfo.getName();
        }
        ActionResult<String> bartextResult = fastGenClient.textGuid();
        if (bartextResult.getCode() != ErrorCode.Success.getCode()) {
            return null;
        }
        Integer seq=barcodeManageMapper.findMaxSeq(barcodeManageDO.getTotalBarcode(),orgId);
        String newBarcode = bartextResult.getValue();
        barcodeManageDO.setTotalQty(barcodeManageDO.getCurrentQty());
        BarcodeManageDO subBarcodeManageDO = new BarcodeManageDO();
        BeanUtils.copyProperties(barcodeManageDO,subBarcodeManageDO);
        subBarcodeManageDO.setBarcode(newBarcode);
        subBarcodeManageDO.setCreateId(userId);
        subBarcodeManageDO.setCreateName(userName);
        subBarcodeManageDO.setCreateTime(new Date());
        subBarcodeManageDO.setCurrentQty(splitNumVO.getNum());
        subBarcodeManageDO.setSeq(seq+1);
        barcodeManageMapper.insert(subBarcodeManageDO);
        BarcodeManageVO subBarcodeVO=new BarcodeManageVO();
        BeanUtils.copyProperties(subBarcodeManageDO,subBarcodeVO);
        if (barcodeManageDO.getBarcodeStatus().equals(BarcodeStatus.Status.InStorage.toString())){
            warehouseInventorySplitService.splitNumber(orgId,barcodeManageDO.getBarcode(),newBarcode,subBarcodeManageDO.getCurrentQty(),userId);
        }
        barcodeManageDO.setCurrentQty(barcodeManageDO.getCurrentQty().subtract(subBarcodeManageDO.getCurrentQty()));
        barcodeManageMapper.update(barcodeManageDO);
        splitNumVO.setCode(ErrorCode.Success);
        subBarcodeVO.setChildCount(seq+1);
        String locationDesc="";
        WarehouseInboundDO inboundDO = warehouseInboundMapper.selectByOrder(subBarcodeVO.getBillNo(), orgId);
        if(inboundDO!=null){
            locationDesc=barcodeManageMapper.locationDesc(subBarcodeVO.getMaterialsNo(),subBarcodeVO.getOrgId(),inboundDO.getWarehouseCode());
        }
        subBarcodeVO.setLocationDesc(locationDesc);
        return subBarcodeVO;
    }

    @Transactional(rollbackFor = Exception.class)
    public List<BarcodeManageVO> splitPrint(SplitPrintVO splitPrintVO,String userId, String orgId) throws  Exception{
        BarcodeManageDO barcodeManageDO=barcodeManageMapper.item(splitPrintVO.getBarcode(), orgId);
        if(barcodeManageDO==null || barcodeManageDO.getIsDel()){
            splitPrintVO.setCode(ErrorCode.BarcodeNotFound);
            return null;
        }
        if(!barcodeManageDO.getBarcodeStatus().equals(BarcodeStatus.Status.Printed.toString())
                && !barcodeManageDO.getBarcodeStatus().equals(BarcodeStatus.Status.InStorage.toString())
                && !barcodeManageDO.getBarcodeStatus().equals(BarcodeStatus.Status.OutStorage.toString())){
            splitPrintVO.setCode(ErrorCode.BarcodeNotSplit);
            return null;
        }

        //校驗已裝箱条码不能拆分
        if (boxupDetailMapper.countByBarcode(splitPrintVO.getBarcode(), orgId)>0){
            throw new Exception( "条码已装箱，不能拆分" );
        }

        //校验拆分数量
        List<SinglePrintDetailVO> detailVOList = splitPrintVO.getDetailList();
        //校验拆分数量
        if (CollectionUtils.isNotEmpty(detailVOList)){
            for (SinglePrintDetailVO printDetailVO : detailVOList){
                if (printDetailVO.getCurrentQty().compareTo(BigDecimal.ZERO) < 1){
                    throw new Exception( "拆分每包数量不能为0" );
                }
            }
        }else{
            throw new Exception( "拆分包装不能为空" );
        }

        ActionResult userAuth =  authClient.getUserDetail(userId);
        UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
        String userName="";
        if(userInfo!=null){
            userName=userInfo.getName();
        }

        //查询零件英文描述
        String materialsDesEn = "";
        PubMaterialsDO pubMaterialsDO = pubMaterialsMapper.itemByMaterialsNo(barcodeManageDO.getMaterialsNo());
        if (null != pubMaterialsDO && StringUtils.isNotEmpty(pubMaterialsDO.getMaterialsDesEn())){
            materialsDesEn = pubMaterialsDO.getMaterialsDesEn();
        }

        BarcodeManageDO totalBarcodeDO=makeSplitTotalBarcode(barcodeManageDO,userId,userName);
        if (totalBarcodeDO==null){
            splitPrintVO.setCode(ErrorCode.IllegalArument);
            return null;
        }
        List<BarcodeManageVO> barcodeManageVOList=new ArrayList<>();
        BarcodeManageVO totalBarcodeVO=new BarcodeManageVO();
        BeanUtils.copyProperties(totalBarcodeDO,totalBarcodeVO);
        String locationDesc="";
        WarehouseInboundDO inboundDO = warehouseInboundMapper.selectByOrder(totalBarcodeDO.getBillNo(), orgId);
//        if(inboundDO.getStatus()==2)
//        {
//            throw new Exception("单据已完成");
//        }
//        if(inboundDO.getStatus()==3)
//        {
//            throw new Exception("单据已结单");
//        }
        if(inboundDO!=null){
            locationDesc=barcodeManageMapper.locationDesc(totalBarcodeDO.getMaterialsNo(),totalBarcodeDO.getOrgId(),inboundDO.getWarehouseCode());
        }
        List<String> sourceIds=new ArrayList<>();
        WarehouseDeliveryRecordDO warehouseDeliveryRecordDO = new WarehouseDeliveryRecordDO();
        if(barcodeManageDO.getBarcodeStatus().equals(BarcodeStatus.Status.OutStorage.toString())){
            List<WarehouseDeliveryRecordDO> records = warehouseDeliveryRecordMapper.findLastRecord(barcodeManageDO.getBarcode(),orgId);
            if(records != null && records.size() > 0){
                // TODO: 2021/4/15 查询条码对应采购合同号、机型、目的地，考虑合并条码出库
                List<String> orderNos = records.stream().map(WarehouseDeliveryRecordDO::getBusinessOrder).distinct().collect(Collectors.toList());
                CompanyInfoDO companyInfoDO = companyInfoMapper.item(orgId);
                if (orderNos.size() == 1){//未合并
                    if (orderNos.get(0).startsWith("XGFT")){//发货通知单
                        //发运交接单
                        DeliveryNoteVO deliveryNoteVO = deliveryNoteService.itemDetail(orderNos.get(0), totalBarcodeDO.getOrgId(), totalBarcodeDO.getMaterialsNo());
                        totalBarcodeDO.setCountry(deliveryNoteVO.getCountry());
                        if (!CompanyUtil.JCK_SAP_CODE.equals(companyInfoDO.getSapCode())){//非进出口
                            totalBarcodeDO.setPurchaseContractNo(deliveryNoteVO.getPurchaseContractNo());
                            totalBarcodeDO.setMachineModel(deliveryNoteVO.getMachineModel());
                        }
                    }
                    //记录出库记录
                    warehouseDeliveryRecordDO = records.get(0);
                    String codeKey = warehouseDeliveryRecordDO.getBusinessOrder();
                    for (WarehouseDeliveryRecordDO recordDO : records) {
                        if(codeKey.equals(recordDO.getBusinessOrder())){
                            sourceIds.add(recordDO.getId());
                        }
                    }
                } else {// TODO: 2021/4/15 合并条码
                    //强制匹配数量
                    List<BigDecimal> recordAmounts = records.stream().map(WarehouseDeliveryRecordDO::getAmount).collect(Collectors.toList());
                    List<BigDecimal> splitAmounts = detailVOList.stream().map(SinglePrintDetailVO::getCurrentQty).collect(Collectors.toList());
                    boolean flag = recordAmounts.containsAll(splitAmounts) && splitAmounts.containsAll(recordAmounts);
                    if (flag){//匹配上组合拆分详情，查询发货通知单信息
                        SinglePrintDetailVO originDetailVO = detailVOList.get(0);
                        detailVOList = Lists.newArrayList();
                        SinglePrintDetailVO finalDetailVO;
                        for (WarehouseDeliveryRecordDO recordDO : records){
                            finalDetailVO = new SinglePrintDetailVO();
                            BeanUtils.copyProperties(originDetailVO,finalDetailVO);
                            finalDetailVO.setFlag("1");

                            finalDetailVO.setCurrentQty(recordDO.getAmount());
                            if (recordDO.getBusinessOrder().startsWith("XGFT")){//发货通知单
                                //通知单详情
                                DeliveryNoteVO deliveryNoteVO = deliveryNoteService.itemDetail(recordDO.getBusinessOrder(), totalBarcodeDO.getOrgId(), totalBarcodeDO.getMaterialsNo());
                                finalDetailVO.setCountry(deliveryNoteVO.getCountry());
                                if (!CompanyUtil.JCK_SAP_CODE.equals(companyInfoDO.getSapCode())){//非进出口
                                    finalDetailVO.setPurchaseContractNo(deliveryNoteVO.getPurchaseContractNo());
                                    finalDetailVO.setMachineModel(deliveryNoteVO.getMachineModel());
                                }
                            }

                            //记录原出库记录
                            finalDetailVO.setDeliveryRecordVO(BeanUtil.do2bo(recordDO, WarehouseDeliveryRecordVO.class));
                            detailVOList.add(finalDetailVO);
                            sourceIds.add(recordDO.getId());
                        }
                    } else {
                        List<String> recordStrings = recordAmounts.stream().map(r -> r.toString()).collect(Collectors.toList());
                        throw new Exception("该条码为合并出库条码，拆箱数量必须为【"+ StringUtils.join(recordStrings, ",") + "】");
                    }
                }
            }
        }
        totalBarcodeVO.setLocationDesc(locationDesc);
        totalBarcodeVO.setMaterialsDesEn(materialsDesEn);//英文描述
        //合并出库拆箱打印总条码信息无
        totalBarcodeVO.setDestinnation(totalBarcodeDO.getCountry());//国家
        totalBarcodeVO.setBatchNo(totalBarcodeDO.getPurchaseContractNo());//批次号
        totalBarcodeVO.setMachineModel(totalBarcodeDO.getMachineModel());//机型
        barcodeManageVOList.add(totalBarcodeVO);
        List<SplitDetailVO> detailList =new ArrayList<>();
        Integer seq = 0;
        for (SinglePrintDetailVO detail : detailVOList) {
            seq++;
            BarcodeManageDO subBarcodeDO=makeSplitSubBarcode(totalBarcodeDO,barcodeManageDO.getBarcode(),barcodeManageDO.getBarcodeStatus(),detail,userId,userName,seq);
            if(subBarcodeDO==null){
                splitPrintVO.setCode(ErrorCode.IllegalArument);
                throw new Exception("异常");
            }
            barcodeManageMapper.insert(subBarcodeDO);
            BarcodeManageVO subBarcodeVO=new BarcodeManageVO();
            BeanUtils.copyProperties(subBarcodeDO,subBarcodeVO);
            subBarcodeVO.setLocationDesc(locationDesc);
            subBarcodeVO.setMaterialsDesEn(materialsDesEn);//英文描述
            subBarcodeVO.setDestinnation(subBarcodeDO.getCountry());//国家
            subBarcodeVO.setBatchNo(subBarcodeDO.getPurchaseContractNo());//批次号
            if (StringUtils.isNotEmpty(detail.getFlag())){
                subBarcodeVO.setDestinnation(detail.getCountry());//国家
                subBarcodeVO.setBatchNo(detail.getPurchaseContractNo());//批次号
                subBarcodeVO.setMachineModel(detail.getMachineModel());//机型
            }
            barcodeManageVOList.add(subBarcodeVO);
            SplitDetailVO splitDetailVO=new SplitDetailVO();
            splitDetailVO.setNowBarCode(subBarcodeDO.getBarcode());
            splitDetailVO.setNum(subBarcodeDO.getCurrentQty());
            detailList.add(splitDetailVO);
            if(barcodeManageDO.getBarcodeStatus().equals(BarcodeStatus.Status.OutStorage.toString())){
                WarehouseDeliveryRecordDO subDeliveryRecordDO =
                        makeDeliveryRecordDO(StringUtils.isNotEmpty(detail.getFlag()) ?
                                BeanUtil.do2bo(detail.getDeliveryRecordVO(),WarehouseDeliveryRecordDO.class) : warehouseDeliveryRecordDO,subBarcodeDO);
                warehouseDeliveryRecordMapper.insert(subDeliveryRecordDO);
                barcodeManageMapper.updateBarcodeLatestOutTime(subDeliveryRecordDO.getCreateDate(),subBarcodeDO.getOrgId(),subBarcodeDO.getBarcode());
            }
        }
        if(barcodeManageDO.getBarcodeStatus().equals(BarcodeStatus.Status.OutStorage.toString())){
            warehouseDeliveryRecordMapper.remove(sourceIds);
        }
        //已入库、已出库拆分增加库存记录
        if (barcodeManageDO.getBarcodeStatus().equals(BarcodeStatus.Status.InStorage.toString())
                || barcodeManageDO.getBarcodeStatus().equals( BarcodeStatus.Status.OutStorage.toString())){
            SplitVO splitVO=new SplitVO();
            splitVO.setPreBarCode(barcodeManageDO.getBarcode());
            splitVO.setOrgId(barcodeManageDO.getOrgId());
            splitVO.setUserId(userId);
            splitVO.setDetailList(detailList);
            warehouseInventorySplitService.add(splitVO);
        }
        barcodeManageDO.setBarcodeStatus(BarcodeStatus.Status.Split.toString());
        barcodeManageDO.setSplitUser(commonService.getUserName(userId));
        DataDictionaryDO dataDictionaryDO=dataDictionaryMapper.itemByCode(BarcodeStatus.Status.Name.toString(),barcodeManageDO.getBarcodeStatus());
        if(dataDictionaryDO!=null){
            barcodeManageDO.setStatusDesc(dataDictionaryDO.getName());
        }
        barcodeManageMapper.update(barcodeManageDO);
        barcodeManageMapper.insert(totalBarcodeDO);
        splitPrintVO.setCode(ErrorCode.Success);
        for (BarcodeManageVO result: barcodeManageVOList
             ) {
            result.setChildCount(seq);
        }
        return barcodeManageVOList;
    }

    private WarehouseDeliveryRecordDO makeDeliveryRecordDO(WarehouseDeliveryRecordDO soureRecordDO,BarcodeManageDO barcodeManageDO){
        WarehouseDeliveryRecordDO warehouseDeliveryRecordDO=new WarehouseDeliveryRecordDO();
        BeanUtils.copyProperties(soureRecordDO,warehouseDeliveryRecordDO);
        ActionResult<String> textResult=fastGenClient.textGuid();
        if(textResult.getCode()!=ErrorCode.Success.getCode()){
            textResult.setValue(barcodeManageDO.getBarcode());
        }
        String id=textResult.getValue();
        warehouseDeliveryRecordDO.setId(id);
        warehouseDeliveryRecordDO.setBarCode(barcodeManageDO.getBarcode());
        warehouseDeliveryRecordDO.setAmount(barcodeManageDO.getCurrentQty());
        return warehouseDeliveryRecordDO;
    }

    private BarcodeManageDO makeSplitTotalBarcode(BarcodeManageDO barcodeManageDO,String userId,String userName){
        ActionResult<String> textResult=fastGenClient.textGuid();
        if(textResult.getCode()!=ErrorCode.Success.getCode()){
            return null;
        }
        String totalBarcode=textResult.getValue();
        BarcodeManageDO totalBarcodeDO =new BarcodeManageDO();
        BeanUtils.copyProperties(barcodeManageDO,totalBarcodeDO);
        totalBarcodeDO.setBarcode(totalBarcode);
        totalBarcodeDO.setTotalBarcode(totalBarcode);
        totalBarcodeDO.setBarcodeFlag(0);
        totalBarcodeDO.setTotalQty(barcodeManageDO.getCurrentQty());
        totalBarcodeDO.setPrintId(userId);
        totalBarcodeDO.setPrintName(userName);
        totalBarcodeDO.setPrintTime(new Date());
        totalBarcodeDO.setReprintCount(0);
        DataDictionaryDO dataDictionaryDO=dataDictionaryMapper.itemByCode( BarcodeStatus.Status.Name.toString(),totalBarcodeDO.getBarcodeStatus());
        if(dataDictionaryDO!=null){
            totalBarcodeDO.setStatusDesc(dataDictionaryDO.getName());
        }
        totalBarcodeDO.setCreateId(userId);
        totalBarcodeDO.setCreateName(userName);
        totalBarcodeDO.setCreateTime(new Date());
        totalBarcodeDO.setIsDel(false);
        totalBarcodeDO.setIsSeparate(true);
        totalBarcodeDO.setSeq(0);
        totalBarcodeDO.setSourceBarcode(barcodeManageDO.getBarcode());
        return totalBarcodeDO;
    }
    private BarcodeManageDO makeSplitSubBarcode(BarcodeManageDO totalBarcodeManageDO,String sourceBarcode,String status,SinglePrintDetailVO detail,String userId,String userName,Integer seq){

        ActionResult<String> bartextResult = fastGenClient.textGuid();
        if (bartextResult.getCode() != ErrorCode.Success.getCode()) {
            return null;
        }
        String barcode = bartextResult.getValue();
        BarcodeManageDO subBarcodeManageDO = new BarcodeManageDO();
        BeanUtils.copyProperties(totalBarcodeManageDO,subBarcodeManageDO);
        subBarcodeManageDO.setBarcode(barcode);
        subBarcodeManageDO.setBarcodeFlag(1);
        if(detail.getBarcodeDesc()==null){
            detail.setBarcodeDesc(totalBarcodeManageDO.getBarcodeDesc());
        }
        subBarcodeManageDO.setBarcodeDesc(detail.getBarcodeDesc());
        if(detail.getVinid()==null){
            detail.setVinid(totalBarcodeManageDO.getVinid());
        }
        subBarcodeManageDO.setVinid(detail.getVinid());
        if(detail.getOrawyd()==null){
            detail.setOrawyd(totalBarcodeManageDO.getOrawyd());
        }
        subBarcodeManageDO.setOrawyd(detail.getOrawyd());
        subBarcodeManageDO.setCurrentQty(detail.getCurrentQty());
        subBarcodeManageDO.setPrintId(userId);
        subBarcodeManageDO.setPrintName(userName);
        subBarcodeManageDO.setPrintTime(new Date());
        subBarcodeManageDO.setReprintCount(0);
        if(detail.getModel()==null){
            detail.setModel(totalBarcodeManageDO.getModel());
        }
        subBarcodeManageDO.setModel(detail.getModel());
        subBarcodeManageDO.setBarcodeStatus(status);
        DataDictionaryDO detaildataDictionaryDO = dataDictionaryMapper.itemByCode(BarcodeStatus.Status.Name.toString(), subBarcodeManageDO.getBarcodeStatus());
        if (detaildataDictionaryDO != null) {
            subBarcodeManageDO.setStatusDesc(detaildataDictionaryDO.getName());
        }
        subBarcodeManageDO.setCreateId(userId);
        subBarcodeManageDO.setCreateName(userName);
        subBarcodeManageDO.setCreateTime(new Date());
        if(detail.getRemark()==null){
            detail.setRemark(totalBarcodeManageDO.getRemark());
        }
        subBarcodeManageDO.setRemark(detail.getRemark());
        subBarcodeManageDO.setIsDel(false);
        subBarcodeManageDO.setIsSeparate(true);
        subBarcodeManageDO.setSourceBarcode(sourceBarcode);
        subBarcodeManageDO.setSeq(seq);
        return subBarcodeManageDO;
    }

    public ActionResult item4TjCheck(BarcodeManageVO barcodeManageVO,String orgId){
        String barcode = barcodeManageVO.getBarcode();
        if(barcodeManageVO == null){
            LogHelper.error("塔机查询条码信息参数：" + barcode,ErrorCode.AbnormalDetailArgumentError.getCode());
            return ActionResultUtil.actionResult(ErrorCode.WarehouseBarcodeNotFound.getCode(),ErrorCode.WarehouseBarcodeNotFound.getDesc(),ErrorCode.WarehouseBarcodeNotFound.getDesc());
        }

        if(barcodeManageVO.getBarcodeFlag() == 1 && "3".equals(barcodeManageVO.getBarcodeStatus())){
            return new ActionResult(ErrorCode.Failure.getCode(), "条码已拆分","条码已拆分");
        }
        List<String> barcdoeList = new ArrayList<>();
        if (barcodeManageVO.getBarcodeFlag() == 0) { //总条码时查询分条码列表
            barcdoeList.addAll(barcodeManageMapper.findBarcodeByTotalBarcode(barcode, orgId));
        } else {
            barcdoeList.add(barcode);
        }

        List<WarehouseInventoryDO> inventoryDOList = warehouseInventoryMapper.selectByBarCodeList(barcdoeList, orgId, null);
        if(CollectionUtils.isEmpty(inventoryDOList)){
            LogHelper.error("塔机查询条码：" + barcode+"没有对应零件",ErrorCode.AbnormalDetailArgumentError.getCode());
            return ActionResultUtil.actionResult(ErrorCode.WarehouseNotFound.getCode(),ErrorCode.WarehouseNotFound.getDesc(),ErrorCode.WarehouseNotFound.getDesc()); //代表没有此零件
        }
        //先判断库存表里是否有零件，零件数量是否够
        BigDecimal amount = BigDecimal.ZERO;//统计条码对应的总零件数
        for(WarehouseInventoryDO warehouseInventoryDO : inventoryDOList){
            if(warehouseInventoryDO == null || warehouseInventoryDO.getIsOut() == 1 ){
                continue;
            }else if(warehouseInventoryDO.getStatus() == 1){
                continue;
            }else if(warehouseInventoryDO.getAmount().compareTo(BigDecimal.ZERO) <= 0){
                continue;
            }
            amount = amount.add(warehouseInventoryDO.getAmount());
        }

        TjBarcodeManageInfoVO result= new TjBarcodeManageInfoVO();
        result.setCurrentQty(amount);
        result.setBarcode(barcode);
        result.setMaterialsDes(inventoryDOList.get(0).getMaterialName());
        result.setMaterialsNo(inventoryDOList.get(0).getMaterialNo());
        return ActionResultUtil.successActionResult(result);
    }

    public BarcodeManageVO item(String barcode, String orgId){
        BarcodeManageDO barcodeManageDO=barcodeManageMapper.item(barcode, orgId);
        if(barcodeManageDO==null ||barcodeManageDO.getIsDel()){
            return null;
        }
        BarcodeManageVO barcodeManageVO=new BarcodeManageVO();
        BeanUtils.copyProperties(barcodeManageDO,barcodeManageVO);
        return barcodeManageVO;
    }

    /**
     * @Des 条码出库时更新条码信息
     * @Date 2021/2/22 11:52
     * @Author wangzhaoyu
     * @Param []
     * @Return xcmg.device.infra.ErrorCode
     */
    public ErrorCode deliveryUpdateBarcode(String businessOrder,String barcode,BarcodeStatus.Status status, String orgId, String userId,Date outTime) throws Exception {
        BarcodeManageDO barcodeManageDO=barcodeManageMapper.item(barcode, orgId);
        if(barcodeManageDO==null){
            return ErrorCode.BarcodeNotFound;
        }
        barcodeManageDO.setBarcodeStatus(status.toString());
        DataDictionaryDO detaildataDictionaryDO = dataDictionaryMapper.itemByCode( BarcodeStatus.Status.Name.toString(), barcodeManageDO.getBarcodeStatus());
        if (detaildataDictionaryDO != null) {
            barcodeManageDO.setStatusDesc(detaildataDictionaryDO.getName());
        }
        if("2".equals(status.toString())){
            barcodeManageDO.setRowNo(null);
            barcodeManageDO.setRowNoReverse(1);
        }
        barcodeManageDO.setOutboundUser(commonService.getUserName(userId));
        barcodeManageDO.setLatestOutTime(outTime);
        //如果业务单据是发货通知单则判断该通知单是否为前移订单，如果是前移订单则需要标记改条码为前移条码，用于前移条码追踪，
        // 需求（http://10.90.1.198/zentao/story-view-2634.html ， http://10.90.1.198/zentao/story-view-2635.html）
        if(!StringUtils.isEmpty(businessOrder) && businessOrder.length()>4
                && businessOrder.substring(0, 4).equals(BillDesc.DeliveryNo.getDesc())){
            DeliveryNoteDO deliveryNote = deliveryNoteMapper.itemByNo(businessOrder,orgId);
            if(deliveryNote == null){
                log.error("发货通知单号:【{}】+机构代码【{}】未查询导发货通知记录",businessOrder,orgId);
                throw new Exception("为查询到发货通知单记录");
            }
            Integer forward = deliveryNote.getForward();
            if(forward != null && forward.compareTo(ForwardBarcodeLableEnum.FORWARD_BARCODE.getLable()) == 0){
                barcodeManageDO.setForward(ForwardBarcodeLableEnum.FORWARD_BARCODE.getLable());
            }
        }
        return barcodeManageMapper.update(barcodeManageDO)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    /**
     * @Des 入库时更新条码信息
     * @Date 2021/2/23 9:04
     * @Author wangzhaoyu
     * @Param [barcode, status, orgId, userId]
     * @Return xcmg.device.infra.ErrorCode
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode inboundUpdateBarcode(String barcode,BarcodeStatus.Status status, String orgId, String userId,Date inTime){
        BarcodeManageDO barcodeManageDO=barcodeManageMapper.item(barcode, orgId);
        if(barcodeManageDO==null){
            return ErrorCode.BarcodeNotFound;
        }
        barcodeManageDO.setBarcodeStatus(status.toString());
        DataDictionaryDO detaildataDictionaryDO = dataDictionaryMapper.itemByCode( BarcodeStatus.Status.Name.toString(), barcodeManageDO.getBarcodeStatus());
        if (detaildataDictionaryDO != null) {
            barcodeManageDO.setStatusDesc(detaildataDictionaryDO.getName());
        }
        if("2".equals(status.toString())){
            barcodeManageDO.setRowNo(null);
            barcodeManageDO.setRowNoReverse(1);
        }
        barcodeManageDO.setInboundUser(commonService.getUserName(userId));
        barcodeManageDO.setLatestInTime(inTime);
        //条码是否为前移条码，如果是前移条码，入库的时候需要记录条码现在在哪个公司，
        // 需求来源（http://10.90.1.198/zentao/story-view-2635.html）
        recordForwardBarcode(barcodeManageDO);
        return barcodeManageMapper.update(barcodeManageDO)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    /**
     * @Des 需求 http://10.90.1.198/zentao/story-view-2635.html
     * 入库时如果入库的条码是前移条码则把该前移条码最新的归属公司更改为当前的入库公司
     * 注意：因为需求是只追踪原始条码的信息，所以如果是拆分出来的条码则不记录即只记录入库的条码值=原始条码值的记录
     * @Date 2021/2/23 9:10
     * @Author wangzhaoyu
     * @Param [barcodeManageDO]
     * @Return void
     */
    private ErrorCode recordForwardBarcode(BarcodeManageDO barcodeManageDO) {
        if(barcodeManageDO == null){
            return ErrorCode.Success;
        }
        Integer forward = barcodeManageDO.getForward();
        if(forward == null || forward.compareTo(ForwardBarcodeLableEnum.FORWARD_BARCODE.getLable()) != 0){
            return ErrorCode.Success;
        }
        //判断是否为前移条码 ，获取条码的源公司，当前公司，源条码，当前条码，判断是否需要添加归属记录（存在即更新，不存在则新增）
        String forwardBarcodeOrigCode = barcodeManageDO.getForwardBarcodeOrigCode();
        String forwardBarcodeOrigOrgid = barcodeManageDO.getForwardBarcodeOrigOrgid();
        if(StringUtils.isEmpty(forwardBarcodeOrigCode) || StringUtils.isEmpty(forwardBarcodeOrigOrgid)){
            return ErrorCode.Success;
        }
        String orgId = barcodeManageDO.getOrgId();
        String barcode = barcodeManageDO.getBarcode();
        if(!barcode.equals(forwardBarcodeOrigCode)){
            return ErrorCode.Success;
        }
        try{
            //查询前移条码是否已经存在所属，如果不存在则进行新增操作，如果已经存在判断当前所属是否和本次入库的所属相同，如果相同则不操作，如果不同则更新为你最新的所属
            ForwardBarcodeTraceInfoDO forwardBarcodeTraceInfoDO = forwardBarcodeTraceInfoMapper.selectByOriginalAndForwardBarcode(forwardBarcodeOrigOrgid, forwardBarcodeOrigCode);
            if(forwardBarcodeTraceInfoDO != null){
                String belongOrgid = forwardBarcodeTraceInfoDO.getBelongOrgid();
                if(!StringUtils.isEmpty(belongOrgid) && belongOrgid.equals(orgId)){//所属公司没有变化则不更新
                    return ErrorCode.Success;
                }else{//更新条前移条码最新的所属公司为当前入库公司
                    forwardBarcodeTraceInfoMapper.updateBelongOrgid(forwardBarcodeOrigOrgid,forwardBarcodeOrigCode,orgId);
                }
            }else{//新增操作
                String maintenanceType = null;
                //获取条码售卖的第一层公司中，改条码对应的零件的A/B件信息
                BarcodeManageDO originalBarcode = barcodeManageMapper.item(forwardBarcodeOrigCode, forwardBarcodeOrigOrgid);
                if(originalBarcode != null){
                    PriMaterialsDO material = priMaterialsMapper.itemByNo(originalBarcode.getMaterialsNo(), forwardBarcodeOrigOrgid);
                    maintenanceType = material.getMaintenanceType();
                }
                forwardBarcodeTraceInfoDO = new ForwardBarcodeTraceInfoDO();
                forwardBarcodeTraceInfoDO.setBelongOrgid(orgId);
                forwardBarcodeTraceInfoDO.setForwardBarcode(forwardBarcodeOrigCode);
                forwardBarcodeTraceInfoDO.setOriginalOrgid(forwardBarcodeOrigOrgid);
                forwardBarcodeTraceInfoDO.setMaintenanceType(maintenanceType);
                Date createTime = new Date();
                forwardBarcodeTraceInfoDO.setCreateTime(createTime);
                forwardBarcodeTraceInfoDO.setUpdateTime(createTime);
                forwardBarcodeTraceInfoMapper.insert(forwardBarcodeTraceInfoDO);
            }
            return ErrorCode.Success;
        }catch (Exception e){
            log.error("更新前移条码【{}】的当前所属公司异常【{}】",forwardBarcodeOrigCode,e);
            return ErrorCode.Failure;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode updateStatus(String barcode,BarcodeStatus.Status status, String orgId, String userId){
        BarcodeManageDO barcodeManageDO=barcodeManageMapper.item(barcode, orgId);
        if(barcodeManageDO==null){
            return ErrorCode.BarcodeNotFound;
        }
        barcodeManageDO.setBarcodeStatus(status.toString());
        DataDictionaryDO detaildataDictionaryDO = dataDictionaryMapper.itemByCode( BarcodeStatus.Status.Name.toString(), barcodeManageDO.getBarcodeStatus());
        if (detaildataDictionaryDO != null) {
            barcodeManageDO.setStatusDesc(detaildataDictionaryDO.getName());
        }
        if("2".equals(status.toString())){
            barcodeManageDO.setRowNo(null);
            barcodeManageDO.setRowNoReverse(1);
        }
        if(status == BarcodeStatus.Status.InStorage){
            barcodeManageDO.setInboundUser(commonService.getUserName(userId));
        }
        if(status == BarcodeStatus.Status.OutStorage){
            barcodeManageDO.setOutboundUser(commonService.getUserName(userId));
        }
        return barcodeManageMapper.update(barcodeManageDO)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    /**
     * 如果编码和批次不存在则更新条码表中的批次号和供应商编码
     * @param barcode 条码
     * @param orgId 机构ID
     * @param splirId 供应商编码
     * @param batchId 批次号
     * @return 更新结果
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode updateSplirIdAndBatchId(String barcode, String orgId, String splirId, String batchId) {
        try {
            BarcodeManageDO barcodeManageDO = new BarcodeManageDO();
            barcodeManageDO.setBarcode(barcode);
            barcodeManageDO.setOrgId(orgId);
            barcodeManageDO.setBatchId(batchId);
            barcodeManageDO.setSplirid(splirId);
            barcodeManageMapper.updateSplirIdIfNotExist(barcodeManageDO);
            return ErrorCode.Success;
        } catch (Exception e) {
            e.printStackTrace();
            return ErrorCode.Failure;
        }
    }

    /**
     * 如果供应商编码不存在则更新条码表中的供应商编码
     * @param barcode 条码
     * @param orgId 机构ID
     * @param splirId 供应商编码
     * @return
     */
    public ErrorCode updateSplirIdIfNotExist(String barcode, String orgId, String splirId) {
        try {
            BarcodeManageDO barcodeManageDO = new BarcodeManageDO();
            barcodeManageDO.setBarcode(barcode);
            barcodeManageDO.setOrgId(orgId);
            barcodeManageDO.setSplirid(splirId);
            barcodeManageMapper.updateSplirIdIfNotExist(barcodeManageDO);
            return ErrorCode.Success;
        } catch (Exception e) {
            e.printStackTrace();
            return ErrorCode.Failure;
        }
    }

    /**
     * @Author: WangKe
     * @Description: 扫描入库时如果实际入库数量小于条码数量，更新条码数量，并且新增条码
     * @Date: 2018/6/7 0007
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBarcodeNum(BarcodeManageDO barcode, BigDecimal realAmount, String orgId)throws Exception{
        if(barcode == null){
            return false;
        }
        boolean success = barcodeManageMapper.updateSelfBarcodeQty(realAmount, barcode.getBarcode(), orgId)>0;
        if(!success){
            throw new Exception("更新条码数量失败");
        }
        Integer seq = barcodeManageMapper.findMaxSeq(barcode.getTotalBarcode(), orgId)+1;

        BarcodeManageDO barcodeManageDO = new BarcodeManageDO();
        BeanUtils.copyProperties(barcode, barcodeManageDO);
        barcodeManageDO.setBarcode(fastGenClient.textGuid().getValue());
        barcodeManageDO.setSeq(seq);
        barcodeManageDO.setCurrentQty(barcode.getCurrentQty().subtract(realAmount));
        success = barcodeManageMapper.insert(barcodeManageDO)>0;
        if(!success){
            throw new Exception("拆分条码失败");
        }

        //如果条码是已入库状态，在库存里也插入拆分条码
        if("1".equals(barcode.getBarcodeStatus())){
            WarehouseInventoryDO warehouseInventoryDO = warehouseInventoryMapper.selectByBarCode(barcode.getBarcode(), orgId);
            if(warehouseInventoryDO == null){
                throw new Exception("未在库存中找到记录");
            }
            warehouseInventoryDO.setAmount(realAmount);
            success = warehouseInventoryMapper.updateByPrimaryKeySelective(warehouseInventoryDO)>0;
            if(!success){
                throw new Exception("更新库存数量失败");
            }
            WarehouseInventoryDO temp = new WarehouseInventoryDO();
            BeanUtils.copyProperties(warehouseInventoryDO, temp);
            temp.setId(fastGenClient.textGuid().getValue());
            temp.setBarCode(barcodeManageDO.getBarcode());
            temp.setAmount(barcodeManageDO.getCurrentQty());
            temp.setCreateDate(new Date());
            temp.setLastChangeDate(new Date());
            success = warehouseInventoryMapper.insert(temp)>0;
            if(!success){
                throw new Exception("更新库存数量失败");
            }
        }

        return true;
    }

//    public BarcodeManageVO checkBarcode(String barcode){
//        BarcodeManageVO barcodeVO = new BarcodeManageVO();
////        PageHelperPlus.orderBy("CREATE_TIME asc");
////        List<BarcodeManageDO> list = barcodeManageMapper.itemByBarcode(barcode);
////        if(ListUtil.isNullOrEmpty(list)){
////            barcodeVO.setFakeCheckStatus("该条码不存在，非徐工正品备件");
////            return barcodeVO;
////        }
////        BarcodeManageDO barcodeManageDO = list.get(0);
////        // 查询超过5次隐藏相关信息
//////        if (barcodeManageDO.getCheckNum() > 5) {
//////            barcodeVO.setFakeCheckStatus("数码为真，但已经超过最大查询次数");
//////            return barcodeVO;
//////        }
////
////        if(barcodeManageDO.getFirstCheckDate() == null){
////            barcodeManageDO.setFirstCheckDate(new Date());
////        }
////        barcodeManageDO.setCheckNum(barcodeManageDO.getCheckNum()+1);
////
////        String handleId = fakeCheckHandleMapper.getByBarcode(barcode);
////        if (StringUtils.isNotBlank(handleId)) {
////            barcodeVO.setHandleUrl(handleUrl + handleId);
////        }
////
////        boolean success = barcodeManageMapper.update(barcodeManageDO)>0;
////        if(!success){
////            return barcodeVO;
////        }
////        BeanUtils.copyProperties(barcodeManageDO, barcodeVO);
////
////        /*if (barcodeManageDO.getCheckNum() > 1) {
////            barcodeVO.setFakeCheckStatus("非首次查询，谨防假冒");
////        } else {
////            barcodeVO.setFakeCheckStatus("备件为正品，且首次查询");
////        }*/
////        barcodeVO.setFakeCheckStatus("备件为正品");
//        return barcodeVO;
//    }

    @Transactional
    public List<BarcodeManageVO> singlePurchasePrint(SinglePrintVO singlePrintVO, String userId, String orgId) throws Exception{
        ActionResult<String> textResult=fastGenClient.textGuid();
        if(textResult.getCode()!=ErrorCode.Success.getCode()){
            singlePrintVO.setErrorCode(ErrorCode.IllegalArument);
            return new ArrayList<>();
        }
        String totalBarcode=textResult.getValue();
        ActionResult userAuth = authClient.getUserDetail(userId);
        UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
        String userName="";
        if(userInfo!=null){
            userName=userInfo.getName();
        }
        if(StringUtil.isEmpty(singlePrintVO.getBillNo())){
            singlePrintVO.setErrorCode(ErrorCode.AbnormalInNotFound);
            return new ArrayList<>();
        }
        PurchaseRequestDetailDO requestDetailDO = purchaseRequestDetailMapper.findByBillIdAndMaterialNo(singlePrintVO.getBillId(), singlePrintVO.getMaterialsNo(), singlePrintVO.getRowNo());
        if(requestDetailDO == null){
            singlePrintVO.setErrorCode(ErrorCode.IllegalArument);
            return new ArrayList<>();
        }
        BigDecimal leftNum = requestDetailDO.getQty().subtract(requestDetailDO.getPrintNum());
        if(singlePrintVO.getTotalQty()==null){
            singlePrintVO.setErrorCode(ErrorCode.BarcodeTotalQtyNull);
            return new ArrayList<>();
        }
        if(singlePrintVO.getTotalQty().equals(BigDecimal.ZERO)){
            singlePrintVO.setErrorCode(ErrorCode.BarcodeTotalQtyError);
            return new ArrayList<>();
        }
        if(singlePrintVO.getTotalQty().compareTo(leftNum)>0){
            singlePrintVO.setErrorCode(ErrorCode.BarcodeLeftNotError);
            return new ArrayList<>();
        }
        List<BarcodeManageVO> results=new ArrayList<>();
        BarcodeManageVO barcodeManageVO=new BarcodeManageVO();
        singlePrintVO.setRowNo(null);
        BarcodeManageDO barcodeManageDO=makeTotalSingleBarcode(singlePrintVO,totalBarcode,orgId,userId,userName);
        barcodeManageMapper.insert(barcodeManageDO);
        BeanUtils.copyProperties(barcodeManageDO,barcodeManageVO);
        results.add(barcodeManageVO);
        Integer i=0;
        for (SinglePrintDetailVO detailVO:singlePrintVO.getDetailList()) {
            if(detailVO.getCurrentQty().equals(0)){
                continue;
            }
            i++;
            ActionResult<String> bartextResult=fastGenClient.textGuid();
            if(bartextResult.getCode()!=ErrorCode.Success.getCode()){
                throw new Exception("异常");
            }
            String barcode=bartextResult.getValue();
            BarcodeManageVO subBarcodeManageVO=new BarcodeManageVO();
            BarcodeManageDO subBarcodeManageDO=makeSubSingleBarcode(singlePrintVO,detailVO,barcode,totalBarcode,orgId,userId,userName,i,1);
            barcodeManageMapper.insert(subBarcodeManageDO);
            BeanUtils.copyProperties(subBarcodeManageDO,subBarcodeManageVO);
            results.add(subBarcodeManageVO);
        }

        BigDecimal totalNum = requestDetailDO.getPrintNum().add(barcodeManageDO.getTotalQty());
        if(requestDetailDO.getQty().compareTo(totalNum) == 0){
            requestDetailDO.setPrintState(2);
        }else{
            requestDetailDO.setPrintState(1);
        }
        requestDetailDO.setPrintNum(totalNum);
        purchaseRequestDetailMapper.update(requestDetailDO);
        purchaseRequestMapper.updatePrintState(requestDetailDO.getBillId(), purchaseRequestDetailMapper.findPrintStatus(requestDetailDO.getBillId()));
        singlePrintVO.setErrorCode(ErrorCode.Success);
        for (BarcodeManageVO result:results
        ) {
            result.setChildCount(i);
        }
        return results;
    }

    @Transactional(rollbackFor = Exception.class)
    public List<BarcodeManageVO> singleDirectPrint(SinglePrintVO singlePrintVO, String userId, String orgId) throws Exception {
        PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(singlePrintVO.getMaterialsNo(), orgId);
        if (priMaterialsDO == null) {
            throw new Exception("零件编码不存在");
        }
        singlePrintVO.setMaterialsDes(priMaterialsDO.getMaterialsDes());
        singlePrintVO.setBillNo(genDocumentService.getDocumentNo(BillDesc.DirectBill));
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult.getCode() != ErrorCode.Success.getCode()) {
            singlePrintVO.setErrorCode(ErrorCode.IllegalArument);
            return new ArrayList<>();
        }
        String totalBarcode = textResult.getValue();
        ActionResult userAuth = authClient.getUserDetail(userId);
        UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
        String userName = "";
        if (userInfo != null) {
            userName = userInfo.getName();
        }
        List<BarcodeManageVO> results = new ArrayList<>();
        int i = 0;
        BarcodeManageVO barcodeManageVO = new BarcodeManageVO();
        singlePrintVO.setRowNo(null);
        BarcodeManageDO barcodeManageDO = makeTotalSingleBarcode(singlePrintVO, totalBarcode, orgId, userId, userName);
        barcodeManageMapper.insert(barcodeManageDO);
        BeanUtils.copyProperties(barcodeManageDO, barcodeManageVO);
        results.add(barcodeManageVO);

        for (SinglePrintDetailVO detailVO : singlePrintVO.getDetailList()) {
            if (detailVO.getCurrentQty().equals(0)) {
                continue;
            }
            i++;
            ActionResult<String> bartextResult = fastGenClient.textGuid();
            if (bartextResult.getCode() != ErrorCode.Success.getCode()) {
                throw new Exception("异常");
            }
            String barcode = bartextResult.getValue();
            BarcodeManageVO subBarcodeManageVO = new BarcodeManageVO();
            BarcodeManageDO subBarcodeManageDO = makeSubSingleBarcode(singlePrintVO, detailVO, barcode, totalBarcode, orgId, userId, userName, i, 1);
            barcodeManageMapper.insert(subBarcodeManageDO);
            BeanUtils.copyProperties(subBarcodeManageDO, subBarcodeManageVO);
            results.add(subBarcodeManageVO);
        }
        singlePrintVO.setErrorCode(ErrorCode.Success);
        for (BarcodeManageVO result:results) {
            result.setChildCount(i);
        }
        return results;
    }

    @Transactional(rollbackFor = Exception.class)
    public void directPrintExport(String materialsNo, BigDecimal totalQty, String detailListStr, String userId, String orgId)throws Exception{
        SinglePrintVO singlePrintVO = new SinglePrintVO();
        singlePrintVO.setMaterialsNo(materialsNo);
        singlePrintVO.setTotalQty(totalQty);
        singlePrintVO.setDetailList(JsonUtil.jsonToList(detailListStr, SinglePrintDetailVO[].class));
        List<BarcodeManageVO> doList = null;
        try {
            doList = this.singleDirectPrint(singlePrintVO, userId, orgId);
        }catch (Exception e){
            LogHelper.monitor(e.getMessage());
        }
        if(ListUtil.isNullOrEmpty(doList)){
            return;
        }
        String title = "直投条码导出";
        String[] rowsName = new String[]{"序号","条码","总条码","条码标识","单据编号",
                "VIN码", "图号", "零件编码", "零件名称","总条码的总数量","当前条码数量","条码状态"};
        List<Object[]>  dataList = new ArrayList<Object[]>();
        Object[] objs;
        for (int i = 0; i < doList.size(); i++) {
            BarcodeManageVO exportDO = doList.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i+1;
            objs[1] = exportDO.getBarcode();//barcodePrefixUrl
            objs[2] = exportDO.getTotalBarcode();
            objs[3] = exportDO.getBarcodeFlag()==0?"总条码":"分条码";
            objs[4] = exportDO.getBillNo();
            objs[5] = exportDO.getVinid();
            objs[6] = exportDO.getOrawyd();
            objs[7] = exportDO.getMaterialsNo();
            objs[8] = exportDO.getMaterialsDes();
            objs[9] = exportDO.getTotalQty();
            objs[10] = exportDO.getCurrentQty();
            objs[11] = exportDO.getStatusDesc();
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    public void directPrintExportBatch(String materialsNo, BigDecimal totalQty, Integer totalSize, String detailListStr, String userId, String orgId) throws Exception {
        barcodeBatchPrintService.directPrintExportBatch(materialsNo, totalQty, totalSize, detailListStr, userId, orgId);
    }

    /**
     * @Author: WangKe
     * @Description: 为浪金提供条码查询接口
     * @Date: 2018/9/30 0030
     */
    public List<BarcodeManageVO> listForLJ(String billNo, String orgId){
        List<BarcodeManageVO> dataList = new ArrayList<>();
        BarcodeManageVO record = new BarcodeManageVO();
        record.setBillNo(billNo);
        record.setBarcodeFlag(1);
        record.setOrgId(orgId);
        List<BarcodeManageDO> list = barcodeManageMapper.list(record);
        if(ListUtil.isNullOrEmpty(list)){
            return dataList;
        }
        for(BarcodeManageDO barcodeManageDO : list){
            BarcodeManageVO barcodeManageVO = new BarcodeManageVO();
            barcodeManageVO.setBarcode(barcodeManageDO.getBarcode());//barcodePrefixUrl
            barcodeManageVO.setMaterialsNo(barcodeManageDO.getMaterialsNo());
            barcodeManageVO.setMaterialsDes(barcodeManageDO.getMaterialsDes());
            barcodeManageVO.setCurrentQty(barcodeManageDO.getCurrentQty());
            barcodeManageVO.setBillNo(barcodeManageDO.getBillNo());
            barcodeManageVO.setSeq(barcodeManageDO.getSeq());
            dataList.add(barcodeManageVO);
        }
        return dataList;
    }

    /** 
    * @Desc   处理进出口条码信息
    * @Author Mr.dong 
    * @Date   2021/3/3 13:48
    */ 
    private void preJckInfo(BarcodeManageDO barcodeManageDO){
        //判断是否进出口，进出口需将采购合同号等保存
        CompanyInfoDO companyInfoDO = companyInfoMapper.item(barcodeManageDO.getOrgId());
        //进出口
        if (CompanyUtil.JCK_SAP_CODE.equals(companyInfoDO.getSapCode())){
            if (barcodeManageDO.getBillNo().startsWith(BillDesc.AbnoramlIn.getDesc())){//其他入库
                AbnormalInDetailDO abnormalInDetailDO = abnormalInDetailMapper.getByMaterialsNo(barcodeManageDO.getMaterialsNo(),barcodeManageDO.getBillNo());
                if (null != abnormalInDetailDO){
                    barcodeManageDO.setCountry(abnormalInDetailDO.getCountry());
                    barcodeManageDO.setMachineModel(abnormalInDetailDO.getMachineModel());
                    barcodeManageDO.setPurchaseContractNo(abnormalInDetailDO.getPurchaseContractNo());
                    //查询零件英文描述
                    String materialsNo = barcodeManageDO.getMaterialsNo();
                    String materialsDesEn = "";
                    List<PubMaterialsDO> pubMaterialsDOS = pubMaterialsMapper.selectByMaterialsNos(Lists.newArrayList(materialsNo));
                    if (org.apache.commons.collections.CollectionUtils.isNotEmpty(pubMaterialsDOS)) {
                        materialsDesEn = pubMaterialsDOS.get(0).getMaterialsDesEn();
                    }
                    barcodeManageDO.setMaterialsDesEn(materialsDesEn);
                }
            }else if (barcodeManageDO.getBillNo().startsWith(BillDesc.PurchaseInbound.getDesc())){//采购入库
                PurchaseInboundPrintVO purchaseInboundPrintVO = purchaseRequestDetailMapper.getJckInfoByMaterialsNo(barcodeManageDO.getOrgId(),barcodeManageDO.getMaterialsNo(),barcodeManageDO.getBillNo());
                if (null != purchaseInboundPrintVO){
                    barcodeManageDO.setCountry(purchaseInboundPrintVO.getCountry());
                    barcodeManageDO.setMachineModel(purchaseInboundPrintVO.getMachineModel());
                    barcodeManageDO.setPurchaseContractNo(purchaseInboundPrintVO.getPurchaseContractNo());
                    barcodeManageDO.setMaterialsDesEn(purchaseInboundPrintVO.getMaterialsDesEn());
                }
            }
        }
    }
    
    public void setPullRecord() throws Exception {
        TaskRecordDO taskRecordDO = new TaskRecordDO();
        taskRecordDO.setId(getId());
        taskRecordDO.setType(String.valueOf(TaskRecordEnum.PULL_BARCODE.getCode()));
        taskRecordDO.setTypeName(TaskRecordEnum.PULL_BARCODE.getDesc());
        taskRecordDO.setTime(new Date());
        taskRecordMapper.insert(taskRecordDO);
    }
    
//    public void manualPullInfos(BarcodePullCondition barcodePullCondition) throws Exception {
//        if (Integer.valueOf(1).equals(barcodePullCondition.getResetFlag())) {
//            if (barcodePullCondition.getResetStartTime() == null || barcodePullCondition.getResetEndTime() == null) {
//                throw new Exception("重置起始时间或重置结束时间不能为空");
//            }
//            /**
//             String reg = "^([1-9]\\d{3}-)(({0,1}[1-9]-)|([1][0-2]-))(([0-3]{0,1}[0-9]))$";
//             if(!Pattern.matches(reg, barcodePullCondition.getResetStartTime()) || !Pattern.matches(reg, barcodePullCondition.getResetEndTime())) {
//             throw new Exception("重置起始时间或重置结束时间格式不正确，正确格式为：yyyy-MM-dd");
//             }
//             */
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//            try {
//                format.parse(barcodePullCondition.getResetStartTime());
//                format.parse(barcodePullCondition.getResetEndTime());
//            } catch (Exception e) {
//                throw new Exception("重置起始时间或重置结束时间格式不正确，正确格式为：yyyy-MM-dd");
//            }
//            resetReadFlag(barcodePullCondition);
//            pullInfos();
//        } else {
//            pullInfos();
//        }
//    }
    
//    public void pullInfos() throws Exception {
//        ActionResult<Integer> countResult = erpSyncClient.pullCount();
//        if (ErrorCode.Success.getCode() == countResult.getCode()) {
//            int count = countResult.getValue();
//            if (count > 0) {
//                int remainder = count % 50;
//                int pageSize = count / 50;
//                if (remainder > 0) {
//                    pageSize = pageSize + 1;
//                }
//                for (int i = 0; i < pageSize; i++) {
//                    int start = i * 50;
//                    int end = (i + 1) * 50;
//                    ActionResult<List<ManagerCodeInfo>> result = erpSyncClient.pullManagerCodeInfos(start, end);
//                    if (ErrorCode.Success.getCode() == result.getCode()) {
//                        List<ManagerCodeInfo> managerCodeInfos = result.getValue();
//                        if (CollectionUtils.isNotEmpty(managerCodeInfos)) {
//                            List<String> notSyncInfos = new ArrayList<String>();
//                            for (ManagerCodeInfo managerCodeInfo : managerCodeInfos) {
//                                convertManagerCodeInfo(managerCodeInfo, notSyncInfos);
//                            }
//                            List<ManagerCodeInfo> syncManagerCodeInfos = new ArrayList<ManagerCodeInfo>();
//                            for (ManagerCodeInfo managerCodeInfo : managerCodeInfos) {
//                                if (managerCodeInfo.getSczldcode() == null || !notSyncInfos.contains(managerCodeInfo.getSczldcode())) {
//                                    syncManagerCodeInfos.add(managerCodeInfo);
//                                }
//                            }
//                            erpSyncClient.updateManagerCodeSyncFlag(syncManagerCodeInfos);
//                            //pullInfos();
//                        }
//                    }
//                }
//            }
//        }
//    }

//    private void convertManagerCodeInfo(ManagerCodeInfo managerCodeInfo, List<String> notSyncInfos) throws Exception {
//        PurchaseRequestDO purchaseRequestDO = purchaseRequestMapper.itemByBillNo(managerCodeInfo.getSczldcode());
//        if (purchaseRequestDO != null) {
//            List<SendBillDetailWithBillNoDO> detailDOs = sendBillDetailMapper.getSendDetailByPurchaseNo(managerCodeInfo.getSczldcode(), managerCodeInfo.getMaterialcode());
//            if (CollectionUtils.isNotEmpty(detailDOs)) {
//                BarcodeManageDO barcodeManageDO = convertBarCode(detailDOs.get(0), managerCodeInfo);
//                barcodeManageMapper.mergeInto(barcodeManageDO);
//            } else {
//                notSyncInfos.add(managerCodeInfo.getSczldcode());
//            }
//        }
//    }
//
//    private BarcodeManageDO convertBarCode(SendBillDetailWithBillNoDO detailDO, ManagerCodeInfo managerCodeInfo) {
//        BarcodeManageDO barcodeManageDO = new BarcodeManageDO();
//        barcodeManageDO.setBarcode(managerCodeInfo.getSnbh());
//        barcodeManageDO.setTotalBarcode(detailDO.getId());
//        barcodeManageDO.setOrgId(detailDO.getReceiveOrgId());
//        barcodeManageDO.setBillType(null);
//        barcodeManageDO.setBillId(null);
//        barcodeManageDO.setBillNo(detailDO.getSendOrder());
//        barcodeManageDO.setBarcodeFlag(1);
//        barcodeManageDO.setMaterialsNo(managerCodeInfo.getMaterialcode());
//        barcodeManageDO.setMaterialsDes(managerCodeInfo.getMaterialname());
//        barcodeManageDO.setTotalQty(detailDO.getRealQty());
//        barcodeManageDO.setCurrentQty(managerCodeInfo.getQuantity());
//        barcodeManageDO.setLeftQty(null);
//        barcodeManageDO.setWarehouseCode(null);
//        barcodeManageDO.setPrintId(null);
//        barcodeManageDO.setPrintName(null);
//        barcodeManageDO.setPrintTime(new Date());
//        barcodeManageDO.setReprintCount(0);
//        barcodeManageDO.setBarcodeStatus(BarcodeStatus.Status.Printed.toString());
//        barcodeManageDO.setRowNo(null);
//        barcodeManageDO.setStatusDesc("已打印");
//        barcodeManageDO.setCreateId(null);
//        barcodeManageDO.setCreateName(null);
//        barcodeManageDO.setCreateTime(new Date());
//        barcodeManageDO.setIsDel(false);
//        barcodeManageDO.setIsSeparate(false);
//        barcodeManageDO.setSeq(0);
//        return barcodeManageDO;
//    }
//
//    /**
//     * 重置拉取价格方案标记
//     */
//    private void resetReadFlag(BarcodePullCondition barcodePullCondition) {
//        ResetTimeConditionVO resetTimeConditionVO = new ResetTimeConditionVO();
//        resetTimeConditionVO.setResetStartTime(barcodePullCondition.getResetStartTime());
//        resetTimeConditionVO.setResetEndTime(barcodePullCondition.getResetEndTime());
//        resetTimeConditionVO.setType("4");
//        erpSyncClient.resetReadFlag(resetTimeConditionVO);
//    }
    
    private String getId() throws Exception {
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult == null || textResult.getCode() != 0)
        {
            throw new Exception("生成ID失败!");
        }
        return textResult.getValue();
    }

    @Transactional(rollbackFor=Exception.class)
    public ErrorCode bindBarcode(BindBarCodeVO bindBarCodeVO, String orgId) throws Exception {
        String billNo = bindBarCodeVO.getBillNo();
        SendBillDO sendBillDO = sendBillMapper.itemByBillNo(billNo);
        if (sendBillDO == null) {
            throw new Exception("送货单不存在");
        }
        if (!Integer.valueOf(1).equals(sendBillDO.getIsSubmit())) {
            throw new Exception("送货单未提交，不能绑定条码");
        }
        BarcodeManageDO barcodeManageDO = barcodeManageMapper.item(bindBarCodeVO.getBarcode(), orgId);
        if (barcodeManageDO == null) {
            throw new Exception("条码不存在");
        }
        Integer count = sendBillDetailMapper.getCountBySendOrderAdndMaterialNo(billNo, barcodeManageDO.getMaterialsNo());
        if (count == null || count == 0) {
            throw new Exception("送货单不存在此零件");
        }
        WarehouseInboundDO warehouseInboundDO = warehouseInboundMapper.
                selectByOrder(billNo, orgId);
        if (warehouseInboundDO != null) {
            orgId = warehouseInboundDO.getOrgId();
        }
        if (Integer.valueOf(0).equals(barcodeManageDO.getBarcodeFlag())) {
            String totalBarcode = barcodeManageDO.getTotalBarcode();
            int isBind = barcodeManageMapper.getIsBindCountByTotalBarcode(totalBarcode, orgId);
            if (isBind > 0) {
                throw new Exception("总条码下部分条码已被绑定使用，只能按子条码绑定");
            }
            barcodeManageMapper.bindBarcodeByTotalBarcode(totalBarcode, billNo, orgId);
            Integer bindedCount = barcodeManageMapper.getCountByBillNoAndMaterialNo(billNo, barcodeManageDO.getMaterialsNo());
            if (bindedCount > count) {
                throw new Exception("绑定零件数量超出送货单零件");
            }
        } else {
            int isBind = barcodeManageMapper.bindBarcode(bindBarCodeVO.getBarcode(), billNo, orgId);
            if (isBind == 0) {
                throw new Exception("此零件已被绑定");
            }
            Integer bindedCount = barcodeManageMapper.getCountByBillNoAndMaterialNo(billNo, barcodeManageDO.getMaterialsNo());
            if (bindedCount > count) {
                throw new Exception("绑定零件数量超出送货单零件");
            }
        }
        return ErrorCode.Success;
    }

    /**
     * 根据条码查询条码相关信息（微信端校验正品、管理端追踪链路）
     * @param barCode
     * @param userId
     * @param isWx
     * @return
     */
    public BarCodeCheckView queryBarCodeCheck(String barCode, String userId, boolean isWx) {
        List<BarcodeManageDO> list = barcodeManageMapper.itemByBarcode2(barCode);
        if (ListUtil.isNullOrEmpty(list)) {
            return null;
        }
        BarcodeManageDO bm = list.get(0);
        int times = queryWxQuertTimes(barCode, userId, isWx);
        BarCodeCheckView r = BeanUtil.do2bo(bm, BarCodeCheckView.class);
        //在库的企业ORGID
        r.setOrgId(null);
        r.setBarCode(bm.getBarcode());
        r.setWxQueryTimes(times);
        if (isWx) {
            //如果是微信端查询，信息足够了返回
            return r;
        }
        if (null == bm.getBarcodeFlag() || 0 == bm.getBarcodeFlag().intValue()) {
            throw new CommonBusiExceptions("该条码为包装条码，请扫描货物条码");
        }
        if (null != r.getBarcodeStatus() && "1".equalsIgnoreCase(r.getBarcodeStatus())) {
            //在库信息查询
            BarCodeCheckView temp = barcodeWxQueryTimesMapper.queryBarInventoryInfo(barCode);
            if (null != temp) {
                r.setOrgId(temp.getOrgId());
                r.setAmount(temp.getAmount());
                r.setCompanyName(temp.getCompanyName());
                r.setAddress(temp.getAddress());
            }
        }
        List<BarCodeCheckSupply> supplys = barcodeWxQueryTimesMapper.queryBarCodeCheckSupply(barCode);
        if (CollectionUtils.isNotEmpty(supplys)) {
            r.setSupply(supplys.get(0));
        }
        List<BarCodeCheckOutInfo> dealerOutInfoList = barcodeWxQueryTimesMapper.queryDealerBarCodeCheckOutInfo(barCode);
        if (CollectionUtils.isNotEmpty(dealerOutInfoList)) {
            r.setDealerOutInfo(dealerOutInfoList.get(0));
        }
        List<BarCodeCheckOutInfo> fwzOutInfoList = barcodeWxQueryTimesMapper.queryFwzBarCodeCheckOutInfo(barCode);
        if (CollectionUtils.isNotEmpty(fwzOutInfoList)) {
            r.setFwzOutInfo(fwzOutInfoList.get(0));
        }
        return r;
    }

    private int queryWxQuertTimes(String barCode, String userId, boolean isWx) {
        if (isWx) {
            BarcodeWxQueryTimesDO t = new BarcodeWxQueryTimesDO();
            t.setId(commonGenService.textIdWithException());
            t.setBarCode(barCode);
            t.setWxQueryTimes(1);
            t.setCreateUser(userId);
            Date now = new Date();
            t.setCreateTime(now);
            t.setUpdateTime(now);
            t.setUpdateUser(userId);
            barcodeWxQueryTimesMapper.merge(t);
        }
        BarcodeWxQueryTimesDO t = new BarcodeWxQueryTimesDO();
        t.setBarCode(barCode);
        List<BarcodeWxQueryTimesDO> tL = barcodeWxQueryTimesMapper.queryList(t);
        if (CollectionUtils.isEmpty(tL)) {
            return 0;
        } else {
            return tL.get(0).getWxQueryTimes();
        }
    }
}
